package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 *
 * Classe che definisce oggetti per la creazione
 * del tipo xschema relativa a CHAR , VARCHAR
 * @author Gianfranco Murador
 */
public class XmlChar extends XmlTypes {

    public XmlChar() {
    }

    public XmlChar(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData cmd) {

        Element xtype, restriction, maxLength;
        fragment = doc.createDocumentFragment();


        // e' possibile avere più tipi CHAR o VARCHAR,
        // ma con lunghezze diverse
        typeName += "_" + cmd.getDisplaySize();
        cmd.setXschemaTypeName(typeName);

        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName);

        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");
        restriction.setAttribute("base", "xs:string");

        maxLength = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:maxLength");

        Integer length = cmd.getDisplaySize();
        maxLength.setAttribute("value", length.toString());

        xtype.appendChild(restriction);
        restriction.appendChild(maxLength);
        fragment.appendChild(xtype);
    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {

        typeName = cmd.getTypeName();
        if (typeName.equals("CHAR") || typeName.equals("VARCHAR")) {
            buildFragment(cmd);
            return fragment;

        } else {

            return nextType.getSchemaType(cmd);

        }
    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {

        if (baseType.startsWith("CHAR") || baseType.startsWith("VARCHAR")) {
            return value;
        }else{

            return nextType.getXSchemaToJavaType(baseType, value);

        }
    }
}

